import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:test2/base/base_page.dart';
import 'package:test2/model/game.dart';
import 'package:test2/model/map.dart';
import 'package:test2/model/scene.dart';
import 'package:test2/util/bus.dart';

class Item {
  String name;
  String boxName;

  Item(this.name, this.boxName);
}

class MoveDialog extends StatefulWidget {
  const MoveDialog({super.key, required this.boxName, required this.list});

  final String boxName;
  final List<SceneC> list;

  @override
  State<MoveDialog> createState() => _MoveDialogState();
}

class _MoveDialogState extends BaseState<MoveDialog> {
  List<Item> gameList = [];
  List<Item> dataList = [];

  @override
  void initState() {
    Box<Game> box = Hive.box<Game>("game");
    List<Game> games = [];
    games.addAll(box.values);

    gameList.addAll(
      games.map((item) {
        return Item(item.name, "game${item.key}");
      }).toList(),
    );

    dataList.addAll(gameList);

    super.initState();
  }

  String selectGame = "";
  int selectIndex = -1;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 400,
      child: Column(
        children: [
          if (selectGame.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: reset,
                    child: Icon(Icons.arrow_back_ios, size: 16),
                  ),
                  Text(
                    selectGame,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),

                  SizedBox(width: 16),
                ],
              ),
            ),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: List.generate(dataList.length, (index) {
                  var item = dataList[index];
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      itemSelect(index);
                    },
                    child: Opacity(
                      opacity: item.boxName == widget.boxName ? 0.2 : 1,
                      child: Container(
                        height: 30,
                        color: selectIndex == index
                            ? Theme.of(context).focusColor
                            : null,
                        child: Center(child: Text(item.name)),
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(
                onPressed: () {
                  finish();
                },
                child: Text("取消"),
              ),
              TextButton(
                onPressed: () {
                  commit();
                },
                child: Text("确认"),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void itemSelect(int index) async {
    print(index);
    if (selectGame.isEmpty) {
      // 选游戏
      var gameBoxName = dataList[index].boxName;
      Box<MapC> box = await Hive.openBox(gameBoxName);
      List<MapC> maps = [];
      maps.addAll(box.values);

      setState(() {
        selectGame = dataList[index].name;
        dataList.clear();
        dataList.addAll(
          maps.map((item) {
            return Item(item.tip, "${gameBoxName}map${item.key}");
          }).toList(),
        );
      });
    } else {
      if (dataList[index].boxName == widget.boxName) {
        return;
      }
      // 选地图
      setState(() {
        selectIndex = index;
      });
    }
  }

  void reset() {
    setState(() {
      selectIndex = -1;
      selectGame = "";
      dataList.clear();
      dataList.addAll(gameList);
    });
  }

  void commit() async {
    if (selectIndex == -1 || selectGame.isEmpty) {
      showToast("请选择目标地图");
      return;
    }

    String targetBoxName = dataList[selectIndex].boxName;

    Box<SceneC> sourceBox = await Hive.openBox(widget.boxName);
    Box<SceneC> targetBox = await Hive.openBox(targetBoxName);


    await sourceBox.deleteAll(widget.list.map((item) => item.key));
    await targetBox.addAll(widget.list);
    bus.emit(EventType.scene);

    Navigator.pop(context, true);
  }
}
